package org.example.captcha.Controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.captcha.CaptchaApplication;
import org.example.captcha.Constants;
import org.example.captcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CapchaController {

    @Autowired
    private CaptchaProperties captchaProperties;

    private final static long session_valid_timeout = 60 * 1000;
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response, InputStream inputStream){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());

        //禁止缓存
        response.setHeader("Progma","No-cache");
                
        //设置返回的类型
        response.setContentType("image/jpeg");


        String code = lineCaptcha.getCode();


        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
    @RequestMapping("/check")
    public Boolean check(String inputCode,HttpSession session){
        //验证码生成的内容去和用户输入的验证码进行比较
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }

        String savedCode = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if(inputCode.equalsIgnoreCase(savedCode)){
            //判断验证码是否过期
            if(saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout){
                return true;
            }
        }
        return false;
    }

}
